package edu.ustb.controller.goods;


import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import edu.ustb.domain.goods.Goods;
import edu.ustb.service.goods.GoodsListService;
import edu.ustb.service.goods.Impl.GoodsListServiceImpl;
import edu.ustb.view.JsonData;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "GoodsListServlet", value = "/WebContent/goods/goodsList")
public class GoodsListServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/plain;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        System.out.println("Running here!");

        // 获取从前端向后端查询的页数
        String pageNum = request.getParameter("pageNum");
        if(pageNum == null){
            pageNum = "1";
            System.out.println("传送进后端的页码最开始为 空值");
        }
        System.out.println("从前端传送到后端的页码数是: " + pageNum + '\n');
        try {
            GoodsListService goodsListService = new GoodsListServiceImpl();
            PageInfo<Goods> pageInfo = goodsListService.getPageGoodsByPageNum(Integer.parseInt(pageNum));

            System.out.println(pageInfo);
            //JsonData result = JsonData.success("所有商品查询成功！", goodsList);
            JsonData result = JsonData.success("所有商品查询成功！", pageInfo);// 用PageHelper的方法尝试
            System.out.println(JSONObject.toJSONString(result));
             out.write(JSONObject.toJSONString(result));
            out.flush();
            out.close();
        }catch (Exception e){
            e.printStackTrace();
            JsonData result  = JsonData.fail("程序出现异常！");
            out.write(JSONObject.toJSONString(result));
            out.flush();
            out.close();
        }






    }
}
